package edu.hawaii.ics314.ical.view;

import java.util.Objects;

public class ListSelectionView<E> extends AbstractView<E> {
	
	private final String HEADER_TEXT;
	private final String FOOTER_TEXT;
	private final E[] LIST_ITEMS;
	
	@SafeVarargs
	public ListSelectionView(String headerText, String footerText, E...listItems) {
		HEADER_TEXT = (headerText == null ? "" : headerText);
		FOOTER_TEXT = (footerText == null ? "" : footerText);
		LIST_ITEMS = Objects.requireNonNull(listItems);
		if(LIST_ITEMS.length == 0) {
			throw new IllegalArgumentException("list must not be empty");
		}
	}

	@Override
	public void show() {
		String selectionPrompt = "Select an item number (1-" + LIST_ITEMS.length + "): ";
		StringBuilder listText = new StringBuilder();
		if(!HEADER_TEXT.isEmpty()) {
			listText.append(HEADER_TEXT);
			listText.append('\n');
		}
		if(LIST_ITEMS.length > 0) {
			for(int i = 0; i < LIST_ITEMS.length; i++) {
				listText.append(i + 1);
				listText.append(". ");
				listText.append(LIST_ITEMS[i].toString());
				if(i < LIST_ITEMS.length - 1) {
					listText.append("\n");
				}
			}
		}
		if(!FOOTER_TEXT.isEmpty()) {
			listText.append('\n');
			listText.append(FOOTER_TEXT);
			listText.append('\n');
		}
		System.out.println(listText.toString());
		for(;;) {
			System.out.print(selectionPrompt);
			String result = readStdinLine().trim();
			try {
				int selection = Integer.parseInt(result);
				if(selection < 1 || selection > LIST_ITEMS.length) {
					System.out.println("Selection out of range (1-" + LIST_ITEMS.length + ").");
				} else {
					fireOnViewResult(LIST_ITEMS[selection - 1], selection - 1);
					break;
				}
			} catch(NumberFormatException e) {
				System.out.println("Invalid input '" + result + "'");
			}
		}
		
	}

}
